package com.lizhenhua.fmmall.service.timerJob;

import com.github.wxpay.sdk.WXPay;
import com.lizhenhua.fmmall.entity.OrderItem;
import com.lizhenhua.fmmall.entity.Orders;
import com.lizhenhua.fmmall.entity.ProductSku;
import com.lizhenhua.fmmall.mapper.OrderItemMapper;
import com.lizhenhua.fmmall.mapper.OrdersMapper;
import com.lizhenhua.fmmall.mapper.ProductMapper;
import com.lizhenhua.fmmall.mapper.ProductSkuMapper;
import com.lizhenhua.fmmall.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class OrderTimeOutCheck {
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderService orderService;

    // 当前商户信息

    private WXPay wxPay = new WXPay(new MyPayConfig());

    @Scheduled(cron = "0/60 * * * * ?")
    public void checkAmdCloseOrder() {

        //1. 查询超过三十分钟 订单状态依然为待支付 状态的订单
        try {
            Example example = new Example(Orders.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("status", 1);

            // 参照时间  当前时间减去30分钟   查询表中时间小于参照时间 且状态为1 的订单就是超时订单

            Date time = new Date(System.currentTimeMillis() - 30 * 60 * 1000);

            criteria.andLessThan("createTime", time);

            List<Orders> orders = ordersMapper.selectByExample(example);

            //2 先访问微信平台接口， 确认当前最终的支付状态


            for (Orders o : orders
            ) {
                HashMap<String, String> hashMap = new HashMap<>();
                // 拿着每个订单的id 查询状态
                hashMap.put("out_trade_no", o.getOrderId());

                Map<String, String> resp = wxPay.orderQuery(hashMap);

                //2.1如果确实未支付则取消订单  如果已支付呢则修改当前状态为 代发货/已支付 status2
                if ("SUCCESS".equalsIgnoreCase(resp.get("trade_state"))) {
                    Orders orders1 = new Orders();
                    orders1.setOrderId(o.getOrderId());
                    orders1.setStatus("2");
                    // 修改指定字段的内容
                    int i = ordersMapper.updateByPrimaryKeySelective(orders1);
                } else if ("NOTPAY".equalsIgnoreCase(resp.get("trade_state"))) {

                    //2.2 如果确实未支付 则取消订单
                    // a.向微信支付平台发送请求，关闭当前支付链接
                    // 关闭订单

                    // 需要的参数  商户id 和订单号

                    Map<String, String> closeMap = wxPay.closeOrder(hashMap);
                    // {nonce_str=jOemGAZkxVOoNbt6, appid=wx632c8f211f8122c6, sign=701D95A115464A7C493F7F163A10D190, return_msg=OK, result_code=SUCCESS, mch_id=1497984412, return_code=SUCCESS} 返回的值

                    if ("SUCCESS".equalsIgnoreCase(closeMap.get("result_code"))){
                        orderService.closeOrder(o.getOrderId());
                    }

/*
                    //b 修改当前订单  status=6 已关闭  close_type=1 超时未支付
                    Orders orders1 = new Orders();
                    orders1.setOrderId(o.getOrderId());
                    orders1.setStatus("6");// 已关闭的订单
                    orders1.setCloseType(1); // 关闭类型超时未支付
                    // 修改指定字段的内容
                    int i = ordersMapper.updateByPrimaryKeySelective(orders1);

                    //c 还原库存  根据当前订单编号查询快照的信息 （skuId by_count） 修改product_sku表 还原库存

                    Example example2 = new Example(OrderItem.class);
                    Example.Criteria criteria2 = example2.createCriteria();
                    criteria2.andEqualTo("orderId", o.getOrderId());

                    List<OrderItem> orderItems = orderItemMapper.selectByExample(example2);

                    for (OrderItem orderItem: orderItems
                         ) {
                        Example example1 = new Example(ProductSku.class);
                        Example.Criteria criteria1 = example1.createCriteria();
                        criteria1.andEqualTo("skuId", orderItem.getSkuId());

                        // 获取id 获取当前套餐信息
                        ProductSku productSku = productSkuMapper.selectByPrimaryKey(orderItem.getSkuId());
                        // 设置库存
                        productSku.setStock(productSku.getStock()+orderItem.getBuyCounts());
                        // 修改库存
                        int i1 = productSkuMapper.updateByExampleSelective(productSku, example1);

                    }

*/


                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}
